import {createAlova} from "alova";
import adapterFetch from 'alova/fetch';
import store from "@/store";
import cache from "@/utils/cache.ts";
import qs from "qs";
import {showNotify} from "vant";

// alova 实例
const service = createAlova({
    requestAdapter: adapterFetch(),
    baseURL: import.meta.env.VITE_API_URL as any,
    timeout: 60000,
    beforeRequest(method) {
        method.config.headers['Content-Type'] = 'application/json;charset=UTF-8';
        method.config.headers["Accept-Language"] = cache.getLanguage();
        const userStore = store.userStore;
        if (userStore?.token) {
            method.config.headers.Authorization = "Bearer " + userStore.token;
        }
        // 追加时间戳，防止GET请求缓存
        if (method.type.toUpperCase() === "GET") {
            method.config.params = { ...method.config.params, t: new Date().getTime() };
        }
        if (Object.values(method.config.headers).includes("application/x-www-form-urlencoded")) {
            method.data = qs.stringify(method.data);
        }
    },
    responded: {
        onSuccess: async (response, method) => {
            console.log(method)
            if (response.status === 401) {
                store.userStore.logout();
                location.reload();
                return ;
            }
            const res = await response.json();
            // 响应成功
            if (res.code === 0 || res.code === 200) {
                return res;
            }
            // 错误提示
            showNotify({ type: 'danger', message: res.message });

            // 没有权限，如：未登录、登录过期等，需要跳转到登录页
            if (res.code === 401) {
                store.userStore.logout();
                location.reload();
                return ;
            }

            throw new Error(res.message || "Error");
        },
        onError: (error, method) => {
            console.log(method)
            if (error.response.status === 401) {
                store.userStore.logout();
                location.reload();
                return;
            } else {
                if (error.response.status === 400) {
                    showNotify({ type: 'danger', message: error.response.data.message });
                } else {
                    showNotify({ type: 'danger', message: error.message });
                }

                throw new Error(error);
            }
        },
        onComplete: async method => {
            // 处理请求完成逻辑
            console.log(method)
        }
    }
});

// 导出 alova 实例
export default service;
